package com.rayenterprise.kms.widgets;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.rayenterprise.kms.client.remote.GenreRemote;
import com.rayenterprise.kms.domain.KGenre;
import com.rayenterprise.kms.events.AfterGenreNodeChangeEvent;


public class GenreEditTab extends AbstractCustomEditTab {

	private KGenre genre = new KGenre();

	public GenreEditTab(HandlerManager eventBus) {
		super(eventBus);
		// TODO Auto-generated constructor stub
	}

	public GenreEditTab(Object obj, AbstractCustomNode node,
			HandlerManager eventBus) {
		super(obj, node, eventBus);
		// TODO Auto-generated constructor stub
		genre = (KGenre) obj;
		text.setText(genre.getName());
	}

	@Override
	public void customObjectInit() {

		name.setText("Genre Name:");
		tab.setAnimationEnabled(true);
		tab.add(hp, "save genre");
		tab.selectTab(0);

		this.add(tab);
		this.setWidth("350px");
		if (node != null) {
			Button btnDeleteGenre = new Button("Delete");
			HorizontalPanel hpDelete = new HorizontalPanel();
			hpDelete.add(btnDeleteGenre);
			hpDelete.setHeight("100%");
			hpDelete.setHorizontalAlignment(HasAlignment.ALIGN_RIGHT);
			btnDeleteGenre.addClickHandler(new ClickHandler() {

				@Override
				public void onClick(ClickEvent event) {
					if (Window
							.confirm("Are You Sure?\nWant to delete this Genre?")) {
						GenreRemote.Util.getInstance().deleteGenre(genre,
								new AsyncCallback<Void>() {

									@Override
									public void onFailure(Throwable caught) {
										Window.alert(caught
												.getLocalizedMessage());
									}

									@Override
									public void onSuccess(Void result) {
										node.remove();
									}
								});
					}
				}
			});
			tab.add(hpDelete, "Delete");

		}

		button.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				genre.setName(text.getValue());
				GenreRemote.Util.getInstance().saveGenre(genre,
						new AsyncCallback<KGenre>() {

							@Override
							public void onFailure(Throwable caught) {
								// TODO Auto-generated method stub
								name.setText(caught.getMessage());

							}

							@Override
							public void onSuccess(KGenre result) {
								if (node == null) {
									node = new GenreNode(result, eventBus);
									AfterGenreNodeChangeEvent sent = new AfterGenreNodeChangeEvent(
											node);
									eventBus.fireEvent(sent);
								} else {
									node.setLblText(result.getName());
								}

							}
						});

			}
		});

	}

}
